package beans;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;

import modelo.Persona;
import dao.PersonaDao;
import excepciones.DaoException;

@ManagedBean //(name = "LoginBean")
@RequestScoped
public class EditPersonaBean {
	
	@ManagedProperty(value="#{loginBean}")
	private LoginBean loginBean;
	
	@ManagedProperty(value="#{listPersonasBean}")
	private ListPersonasBean listPersonasBean;
	
	private Persona persona;
	private Persona selected;
	
	@PostConstruct
	public void init(){
		this.persona = new Persona(); 
		if (listPersonasBean.getSelected() != null){
			PersonaDao personaDao = new PersonaDao();
			try {
				this.persona = (Persona) personaDao.findById(listPersonasBean.getSelected());
				
			} catch (DaoException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
	}
	
	
	public String save(){
		PersonaDao personaDao = new PersonaDao(persona);
			try {
				personaDao.update();
				personaDao.closeEntityManager();
			} catch (DaoException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		this.getListPersonasBean().setPersonas(null);
		PersonaDao perDao = new PersonaDao();
		try {
			this.getListPersonasBean().setPersonas(perDao.getTodasLasPersonas());
		} catch (DaoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return "irListadoPersonas";
	}


	public Persona getPersona() {
		return persona;
	}


	public void setPersona(Persona persona) {
		this.persona = persona;
	}


	public LoginBean getLoginBean() {
		return loginBean;
	}
	public void setLoginBean(LoginBean loginBean) {
		this.loginBean = loginBean;
	}


	public Persona getSelected() {
		return selected;
	}


	public void setSelected(Persona selected) {
		this.selected = selected;
	}


	public ListPersonasBean getListPersonasBean() {
		return listPersonasBean;
	}


	public void setListPersonasBean(ListPersonasBean listPersonasBean) {
		this.listPersonasBean = listPersonasBean;
	}

	
	
	
	
	
}